package com.pigdroid.adbsqlite;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;


public class CSVIterator implements Iterator<Map<String, String>>{

	public static final CSVIterator EMPTY = new CSVIterator();
	
	List<String> headers = new ArrayList<String>();
	Iterator<String> iterator = null;
	
	private CSVIterator() {
		headers = Collections.emptyList();
		iterator = Collections.emptyIterator();
	}
	
	public CSVIterator(String in) {
		List <String> lines = new ArrayList<String>();
		StringTokenizer tok = new StringTokenizer(in, "\n");
		while (tok.hasMoreTokens()) {
			lines.add(tok.nextToken().trim());
		}
		iterator = lines.iterator();
		if (iterator.hasNext()) {
			tok = new StringTokenizer(iterator.next(), "|");
			while (tok.hasMoreTokens()) {
				headers.add(tok.nextToken());
			}
		}
	}

	public boolean hasNext() {
		return iterator.hasNext();
	}

	public Map<String, String> next() {
		StringTokenizer tok = new StringTokenizer(iterator.next(), "|");
		HashMap<String, String> ret = new HashMap<String, String>();
		Iterator<String> headerIt = headers.iterator();
		while (tok.hasMoreTokens()) {
			String token = tok.nextToken();
			if ("*null*".equals(token)) {
				token = null;
			}
			ret.put(headerIt.next(), token);
		}
		return ret;
	}

	public void remove() {
		throw new UnsupportedOperationException();
	}

	public int findColumn(String name) {
		int ret = headers.indexOf(name);
		return ret + 1;
	}

	public int getHeaderCount() {
		return headers.size();
	}

	public String getHeader(int arg0) {
		return headers.get(arg0 - 1);
	}

}
